package com.sunday.aomicaichang.ui.my;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.AddressListAdapter;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.member.entity.addr.Address;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class AddressListActivity extends BaseActivity {


    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.add_addr)
    LinearLayout addAddr;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;

    private long memberId;
    private List<Address> dataSet = new ArrayList<>();
    private AddressListAdapter adapter;
    private boolean isSelectMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addr_list);
        ButterKnife.bind(this);
        initView();
        getData();
    }

    private void initView() {
        memberId = BaseApp.getInstance().getMember().getId();
        isSelectMode = getIntent().getBooleanExtra("isSelectMode", false);
        title.setText("我的小区");
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new AddressListAdapter(mContext, dataSet);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.horizontal_space_divider)
                .build());
        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.edite:
                        int p = (int) v.getTag();
                        Address address = dataSet.get(p);
                        intent = new Intent(mContext, AddAddressActivity.class);
                        intent.putExtra("address", address);
                        startActivity(intent);
                        break;
                    case R.id.delete:
                        final int p2 = (int) v.getTag();
                        final Address address2 = dataSet.get(p2);
                        final UIAlertView dialog = new UIAlertView(mContext, "温馨提示", "确实删除此收货地址吗", "取消", "确定");
                        dialog.show();
                        dialog.setClicklistener(new UIAlertView.ClickListenerInterface() {
                            @Override
                            public void doLeft() {
                                dialog.dismiss();
                            }

                            @Override
                            public void doRight() {
                                delAddr(address2, p2);
                                dialog.dismiss();
                            }
                        });
                        break;
                    case R.id.choice:
                        int p3 = (int) v.getTag();
                        Address address3 = dataSet.get(p3);
                        setDefaultAddr(address3, p3);
                        for(int i=0;i<dataSet.size();i++){
                            dataSet.get(i).setSelect(false);
                        }
                        address3.setSelect(true);
                        adapter.notifyDataSetChanged();

                        break;
                    case R.id.address_layout:
                        if (isSelectMode) {
                            Address address1 = (Address) v.getTag();
                            Intent data = new Intent();
                            data.putExtra("address", address1);
                            setResult(RESULT_OK, data);
                            finish();
                        }
                        break;
                }
            }
        });
    }

    private void delAddr(Address address, final int p) {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"addressId", "nonce"};
        String[] str2 = new String[]{String.valueOf(address.getId()),nonce};
        showLoadingDialog(0);
        Call<ResultDO> call = MemberClient.getApiAdapter().delAddr(address.getId(), nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "删除成功");
                    getData();

                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);

            }
        });
    }

    private void setDefaultAddr(Address address, final int p) {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"addressId", "nonce"};
        String[] str2 = new String[]{String.valueOf(address.getId()),nonce};
        Call<ResultDO> call = MemberClient.getApiAdapter().setDefaultAddr(address.getId(),nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });

    }


    @OnClick(R.id.add_addr)
    void addAddr() {
        intent = new Intent(mContext, AddAddressActivity.class);
        startActivity(intent);
    }

    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"nonce"};
        String[] str2 = new String[]{nonce};
        showLoadingDialog(0);
        Call<ResultDO<List<Address>>> call = MemberClient.getApiAdapter().getAddrList(nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<Address>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Address>>> call, Response<ResultDO<List<Address>>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                ResultDO<List<Address>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    dataSet.clear();
                    dataSet.addAll(resultDO.getResult());
                    if(dataSet!=null&&dataSet.size()>0)
                        for(int i=0;i<dataSet.size();i++){
                            if(dataSet.get(i).getIsDefault()==1){
                                dataSet.get(i).setSelect(true);
                            }else
                                dataSet.get(i).setSelect(false);
                        }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Address>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }
}
